<script setup lang="ts">
// ----------------------- 导入相关依赖 -----------------------
import { nextTick, onMounted, onUnmounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import SysDialog from '@/components/dialog/SysDialog.vue'
import useDialog from '@/hooks/useDialog'
import useInstance from '@/hooks/useInstance'
import { getDeviceMaterialList } from '@/api/deviceMaterial'
import { Search, Refresh } from '@element-plus/icons-vue'
import { DeviceMaterialQuery, DeviceMaterial } from '@/api/deviceMaterial/type.ts'

// ----------------------- 组件状态定义 -----------------------
const { dialog, onShow, onClose } = useDialog()
const { global } = useInstance()

// 表格高度自适应
const tableHeight = ref(0)

// ----------------------- 表格相关 -----------------------
const tableData = ref<DeviceMaterial[]>([])
const loading = ref(false)
const paginationData = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10,
})

// ----------------------- 查询表单相关 -----------------------
const searchForm = reactive<DeviceMaterialQuery>({
  materialCode: undefined,
  materialName: undefined,
  materialType: undefined,
  current: 1,
  size: 10,
})
// 查询方法
const search = () => {
  paginationData.currentPage = 1
  getTableData()
}

// 重置查询
const reset = () => {
  searchForm.materialCode = undefined
  searchForm.materialName = undefined
  searchForm.materialType = undefined
  search()
}

// ----------------------- 表格数据处理 -----------------------
const getTableData = async () => {
  loading.value = true
  try {
    searchForm.current = paginationData.currentPage
    searchForm.size = paginationData.pageSize
    let res = await getDeviceMaterialList(searchForm)
    if (res && res.data) {
      // 根据API返回结构适配数据
      if (res.data.records) {
        // 如果返回的是分页格式
        tableData.value = res.data.records || []
        paginationData.total = res.data.total || 0
      } else if (Array.isArray(res.data)) {
        // 如果返回的是数组格式
        tableData.value = res.data
        paginationData.total = res.data.length
      } else if (res.data.list) {
        // 如果返回的是另一种分页格式
        tableData.value = res.data.list || []
        paginationData.total = res.data.total || 0
      }
    }
  } catch (error) {
    console.error('获取表格数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 选择设备物料
const handleSelect = (selection: DeviceMaterial[]) => {
  console.log('发送变化选择设备物料', selection)
  emit('handleMaterialSelectionChange', selection)
}

// 确认选择完毕
const confirmMaterial = () => {
  emit('confirmMaterialSelect')
}

// 关闭弹框
const closeDialog = () => {
  onClose()
}

// ----------------------- 生命周期钩子 -----------------------
onMounted(() => {
  dialog.height = 500
  dialog.width = 1200
  dialog.title = '选择设备物料'
  getTableData()
  nextTick(() => {
    tableHeight.value = 380
  })
})

// 监听窗口大小变化
const handleResize = () => {
  nextTick(() => {
    tableHeight.value = 380
  })
}

onMounted(() => {
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

// 添加表格引用
const tableRef = ref()

// 暴露方法给父组件
defineExpose({
  onShow: (preSelectedMaterials = []) => {
    // 如果传入了预选物料列表，设置为已选中状态
    dialog.visible = true
    // 如果有预选物料，设置表格的选中状态
    if (preSelectedMaterials && preSelectedMaterials.length > 0) {
      // 等待表格数据加载完成后设置选中状态
      nextTick(() => {
        setTimeout(() => {
          if (tableRef.value) {
            // 先清除所有选中状态
            tableRef.value.clearSelection()
            // 设置选中状态
            tableData.value.forEach((row) => {
              const isSelected = preSelectedMaterials.some(
                (material: any) => material.id === row.id || material.materialId === row.id)
              if (isSelected) {
                tableRef.value.toggleRowSelection(row, true)
              }
            })
          }
        }, 300)
      })
    }
  },
  onClose,
})

// 定义emit事件
const emit = defineEmits([
  'handleMaterialSelectionChange',
  'confirmMaterialSelect',
  'handleMaterialSelect',
])

// 接收父组件参数
const props = defineProps({
  multiple: {
    type: Boolean,
    default: true,
  },
})

// 点击选择某一行，获取那行的数据
const handleRowClick = (row: DeviceMaterial) => {
  if (!props.multiple) {
    emit('handleMaterialSelect', row)
    closeDialog()
  }
}

// 格式化金额
const formatPrice = (price: string | number | undefined) => {
  if (price === undefined || price === null) return '¥0.00'
  const numPrice = typeof price === 'string' ? parseFloat(price) : price
  if (isNaN(numPrice)) return '¥0.00'
  return `¥${numPrice.toFixed(2)}`
}
</script>

<template>
  <sys-dialog :title="dialog.title"
              :width="dialog.width"
              :visible="dialog.visible"
              :height="dialog.height"
              @onClose="closeDialog"
              @on-confirm="confirmMaterial">
    <template #content>
      <div class="material-dialog-container">
        <el-row :gutter="10">
          <!-- 右侧内容区 -->
          <el-col :span="24">
            <!-- 查询表单区域 -->
            <el-card class="search-card">
              <el-form :inline="true"
                       :model="searchForm"
                       class="search-form">
                <el-form-item label="物料名称">
                  <el-input v-model="searchForm.materialName"
                            placeholder="请输入物料名称" />
                </el-form-item>
                <el-form-item label="物料编码">
                  <el-input v-model="searchForm.materialCode"
                            placeholder="请输入物料编码" />
                </el-form-item>
                <el-form-item label="材质">
                  <el-input v-model="searchForm.materialType"
                            placeholder="请输入材质" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary"
                             @click="search">
                    <el-icon>
                      <Search />
                    </el-icon>
                    查询
                  </el-button>
                  <el-button @click="reset">
                    <el-icon>
                      <Refresh />
                    </el-icon>
                    重置
                  </el-button>
                </el-form-item>
              </el-form>
            </el-card>

            <!-- 表格区域 -->
            <el-table v-loading="loading"
                      :data="tableData"
                      border
                      :height="tableHeight"
                      style="margin-top: 15px"
                      @selection-change="handleSelect"
                      @row-click="handleRowClick"
                      ref="tableRef">
              <el-table-column v-if="multiple"
                               type="selection"
                               width="55" />
              <el-table-column prop="materialCode"
                               label="物料编码"
                               min-width="120"
                               align="center"
                               show-overflow-tooltip />
              <el-table-column prop="materialName"
                               label="物料名称"
                               min-width="150"
                               align="center"
                               show-overflow-tooltip />
              <el-table-column prop="specification"
                               label="规格"
                               min-width="120"
                               show-overflow-tooltip
                               align="center" />
              <el-table-column prop="materialType"
                               label="材质"
                               min-width="100"
                               align="center" />
              <el-table-column prop="unit"
                               label="单位"
                               width="80"
                               align="center" />
              <el-table-column prop="price"
                               label="单价"
                               width="100"
                               align="center">
                <template #default="scope">
                  <span class="price-value">{{ formatPrice(scope.row.price) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="remark"
                               label="备注"
                               min-width="150"
                               show-overflow-tooltip
                               align="center" />
            </el-table>

            <!-- 分页 -->
            <el-pagination v-model:current-page="paginationData.currentPage"
                           v-model:page-size="paginationData.pageSize"
                           :page-sizes="[10, 20, 50]"
                           :total="paginationData.total"
                           layout="total, sizes, prev, pager, next"
                           class="pagination"
                           @size-change="getTableData"
                           @current-change="getTableData" />
          </el-col>
        </el-row>
      </div>
    </template>
  </sys-dialog>
</template>

<style scoped lang="scss">
.material-dialog-container {
  padding: 0 0px;
  box-sizing: border-box;
  height: 100%;
  overflow: hidden;
}

.el-pagination {
  margin-top: 10px;
  justify-content: flex-end;
}

.search-card {
  height: auto;

  :deep(.el-card__body) {
    padding: 10px;
  }
}

:deep(.el-table__row) {
  cursor: pointer;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 10px;
  margin-bottom: 0;
}

:deep(.el-input) {
  width: 180px;
}

.price-value {
  font-weight: 600;
  color: #f56c6c;
}
</style> 